package com.my.netty.service;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.db.Db;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONNull;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import java.sql.JDBCType;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Author: chenzhen
 * Description:
 * Date:    2019/10/26 21:27
 */
public class DataService implements Runnable {

    public DataService(String data) {
        this.data = data;
    }

    private String data;

    @Override
    public void run() {
        long begin = System.currentTimeMillis();
        String name = Thread.currentThread().getName();
        System.out.println("##########正在处理" + name);
        try {
            JSONArray datas = JSONUtil.parseArray(data);
            String delSql = "delete from  fu_sys_task_log where id=?";
            String[][] delIds = new String[datas.size()][1];
            String[] updateSql = new String[1];
            int idx[] = new int[]{0};
            Object[][] update = new Object[datas.size()][];
            datas.forEach(oneData -> {
                JSONObject dataMap = (JSONObject) oneData;
                String table = dataMap.getStr("table");
                String id = dataMap.getStr("id");
                delIds[idx[0]][0] = id;
                dataMap.remove("table");
                dataMap.remove("status");
                StringBuilder bSql = new StringBuilder("insert into " + table + "(");
                StringBuilder vSql = new StringBuilder(" values(");
                List<Object> sp = new ArrayList<>();
                dataMap.forEach((key, val) -> {
                    bSql.append(key).append(",");
                    vSql.append("?").append(",");
                    if (val == JSONNull.NULL) {
                        sp.add(null);
                    } else {
                        sp.add(val);
                    }
                });
                bSql.deleteCharAt(bSql.length() - 1).append(")");
                vSql.deleteCharAt(vSql.length() - 1).append(")");
                updateSql[0] = bSql.append(vSql).toString();
                update[idx[0]] = sp.toArray();
                idx[0]++;
            });
            Db.use().executeBatch(delSql, delIds);
            System.out.println(updateSql[0]);
            Db.use().executeBatch(updateSql[0], update);

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
        }
        System.out.println("##########处理结束" + name + " " + (System.currentTimeMillis() - begin));
    }
}
